#define  _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

ListNode* BuyListNode(LTDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (!newnode)
	{
		perror("BuyListNode");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = newnode->prev = NULL;
	return newnode;
}

ListNode* ListInit()
{
	ListNode* newhead = BuyListNode(0);
	newhead->next = newhead;
	newhead->prev = newhead;
	return newhead;
}

void ListDestory(ListNode* phead)
{
	assert(phead);
}

void ListPrint(ListNode* phead)
{
	assert(phead);

	printf("head<-->");
	ListNode* curr = phead->next;
	while (curr != phead)
	{
		printf("%d<-->", curr->data);
		curr = curr->next;
	}
	printf("\n");
}

void ListPushBack(ListNode* phead, LTDataType x)
{
	ListInsert(phead, x);
}

void ListPushFront(ListNode* phead, LTDataType x)
{
	ListInsert(phead->next, x);
}

void ListPopBack(ListNode* phead)
{
	ListErase(phead->prev);
}

void ListPopFront(ListNode* phead)
{
	ListErase(phead->next);
}

int ListSize(ListNode* phead)
{
	assert(phead);

	int size = 0;
	ListNode* curr = phead->next;
	while (curr != phead)
	{
		size++;
		curr = curr->next;
	}
	return size;
}

ListNode* ListFind(ListNode* phead, LTDataType x)
{
	assert(phead);

	ListNode* curr = phead->next;
	while (curr != phead)
	{
		if (curr->data == x)
			return curr;
		curr = curr->next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);

	ListNode* prev = pos->prev;
	ListNode* newnode = BuyListNode(x);

	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;

}

void ListErase(ListNode* pos)
{
	assert(pos);
	assert(pos->prev != pos->next);

	ListNode* prev = pos->prev;
	ListNode* next = pos->next;

	prev->next = next;
	next->prev = prev;
	free(pos);
}
